package com.yazif.vqa.api.wechat.async;

import com.yazif.vqa.api.wechat.service.WechatApiService;
import com.yazif.vqa.dao.RedisDao;
import com.yazif.vqa.domain.Deal;
import com.yazif.vqa.domain.MessageListEnum;
import com.yazif.vqa.util.RedisKeyUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MessageSender implements InitializingBean {

    @Resource
    private WechatApiService wechatApiService;

    @Resource
    private RedisDao redisDao;

    @Override
    public void afterPropertiesSet() throws Exception {
        Thread thread = new Thread(() -> {
            String key = RedisKeyUtil.getMessageList(MessageListEnum.DEALED);

            while (true) {
                try {
                    System.out.println("Task begin");
                    Deal deal = redisDao.brPop(key);
                    wechatApiService.sendMessage(deal);
                    Thread.sleep(100);
                } catch (Exception e) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

}
